import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

const instance = axios.create({
  // 生产与开发环境的基地址不同,保存在.env.development和.env.production中
  // 使用process.env获取定义的环境变量
  // VUE_APP_BASE_API 会根据npm run dev或npm run build:prod 来判断基地址取什么值
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000
})

instance.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  })

instance.interceptors.response.use(
  (response) => {
    if (response.data instanceof Blob) return response.data
    const { success, message, data } = response.data
    if (success) {
      return data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  async(error) => {
    if (error.response?.status === 401) {
      await store.dispatch('user/loginout')
      router.push('/login')
      Message.error('用户身份过期,请重新登录')
      return Promise.reject(error)
    }
    Message.error(error.message)
    return Promise.reject(error)
  }
)

export default instance
